from fastapi import APIRouter, HTTPException, Query
from kubernetes.client.rest import ApiException
from app.core.k8s import v1_core
from typing import List, Optional
from pydantic import BaseModel
from datetime import datetime

router = APIRouter(prefix="/namespaces")

# 增强的模型定义
class NamespaceMetadata(BaseModel):
    name: str
    uid: str
    creation_timestamp: str
    labels: Optional[dict] = None
    annotations: Optional[dict] = None

class NamespaceStatus(BaseModel):
    phase: str

class Namespace(BaseModel):
    metadata: NamespaceMetadata
    status: NamespaceStatus

class NamespaceList(BaseModel):
    items: List[Namespace]
    total_count: int

class CreateNamespaceRequest(BaseModel):
    name: str
    labels: Optional[dict] = None
    annotations: Optional[dict] = None

# 获取命名空间列表
@router.get("", response_model=NamespaceList)
async def list_namespaces(
    label_selector: Optional[str] = Query(None, description="Label selector for filtering")
):
    try:
        # 获取命名空间列表，支持标签筛选
        if label_selector:
            k8s_namespaces = v1_core.list_namespace(label_selector=label_selector)
        else:
            k8s_namespaces = v1_core.list_namespace()
        
        # 转换为我们的模型
        items = []
        for ns in k8s_namespaces.items:
            items.append(Namespace(
                metadata=NamespaceMetadata(
                    name=ns.metadata.name,
                    uid=ns.metadata.uid,
                    creation_timestamp=str(ns.metadata.creation_timestamp),
                    labels=dict(ns.metadata.labels) if ns.metadata.labels else None,
                    annotations=dict(ns.metadata.annotations) if ns.metadata.annotations else None
                ),
                status=NamespaceStatus(phase=ns.status.phase)
            ))
        
        return NamespaceList(items=items, total_count=len(items))
    except ApiException as e:
        raise HTTPException(status_code=e.status, detail=f"Kubernetes API Error: {e.reason}")
    
# 获取单个命名空间详情
@router.get("/{name}", response_model=Namespace)
async def get_namespace(name: str):
    try:
        # 获取指定命名空间
        namespace = v1_core.read_namespace(name=name)
        
        return Namespace(
            metadata=NamespaceMetadata(
                name=namespace.metadata.name,
                uid=namespace.metadata.uid,
                creation_timestamp=str(namespace.metadata.creation_timestamp),
                labels=dict(namespace.metadata.labels) if namespace.metadata.labels else None,
                annotations=dict(namespace.metadata.annotations) if namespace.metadata.annotations else None
            ),
            status=NamespaceStatus(phase=namespace.status.phase)
        )
    except ApiException as e:
        if e.status == 404:
            raise HTTPException(status_code=404, detail=f"Namespace '{name}' not found")
        raise HTTPException(status_code=e.status, detail=f"Kubernetes API Error: {e.reason}")

# 创建命名空间
@router.post("", response_model=Namespace, status_code=201)
async def create_namespace(request: CreateNamespaceRequest):
    try:
        # 构建命名空间对象
        body = {
            "metadata": {
                "name": request.name,
                "labels": request.labels,
                "annotations": request.annotations
            }
        }
        
        # 创建命名空间
        namespace = v1_core.create_namespace(body=body)
        
        return Namespace(
            metadata=NamespaceMetadata(
                name=namespace.metadata.name,
                uid=namespace.metadata.uid,
                creation_timestamp=str(namespace.metadata.creation_timestamp),
                labels=dict(namespace.metadata.labels) if namespace.metadata.labels else None,
                annotations=dict(namespace.metadata.annotations) if namespace.metadata.annotations else None
            ),
            status=NamespaceStatus(phase=namespace.status.phase)
        )
    except ApiException as e:
        if e.status == 409:
            raise HTTPException(status_code=409, detail=f"Namespace '{request.name}' already exists")
        raise HTTPException(status_code=e.status, detail=f"Kubernetes API Error: {e.reason}")
    
    
# 删除命名空间
@router.delete("/{name}")
async def delete_namespace(name: str):
    try:
        # 删除命名空间
        response = v1_core.delete_namespace(name=name)
        
        return {
            "message": f"Namespace '{name}' deleted successfully",
            "status": response.status
        }
    except ApiException as e:
        if e.status == 404:
            raise HTTPException(status_code=404, detail=f"Namespace '{name}' not found")
        raise HTTPException(status_code=e.status, detail=f"Kubernetes API Error: {e.reason}")
    
    
# 获取命名空间统计信息
@router.get("/{name}/stats")
async def get_namespace_stats(name: str):
    try:
        # 检查命名空间是否存在
        v1_core.read_namespace(name=name)
        
        # 获取命名空间中的资源数量（这里以Pod为例）
        pods = v1_core.list_namespaced_pod(namespace=name)
        services = v1_core.list_namespaced_service(namespace=name)
        
        return {
            "namespace": name,
            "pod_count": len(pods.items),
            "service_count": len(services.items),
            "total_resources": len(pods.items) + len(services.items)
        }
    except ApiException as e:
        if e.status == 404:
            raise HTTPException(status_code=404, detail=f"Namespace '{name}' not found")
        raise HTTPException(status_code=e.status, detail=f"Kubernetes API Error: {e.reason}")